var config = require("../../config");
var Page = require("../models/page");
var Cases = require("../models/cases");
var cate = require("../controllers/category");
var nav = require("../controllers/navigator");
var link = require("../controllers/friendlylinks");
var Category = require("../models/category");
var laypage=require("laypage");
var async = require('async');

//课程列表
exports.list = function (req, res) {
	var pageSize = 10; //每页显示条数
	var page = req.params.num - 1 || 0;
	Cases.find().count().exec(function (err, sum) {
		Cases.find().limit(pageSize).skip(pageSize * page).sort({_id: -1}).populate("categoryId","CateName").exec(function (err, _cases) {
			Category.find({original:1}, function (err, _category) {
				res.render('admin/casesList', {
					title: '课程列表',
					category: _category,
					laypage: laypage({
						curr: req.params.num || 1,
						url: req.url, //必传参数，获取当前页的url
						groups: 5,
						pages: Math.ceil(sum/pageSize), //分页总数你需要通过sql查询得到
						prev: '‹',
						next: '›'
					}),
					cases:_cases,
					pagesize: sum
				})
			})
		});
	});
}

//项目案例
exports.add = function (req, res) {
	Category.find({original:2}).sort({Sort: 1}).exec(function (err, _category) {
		res.render('admin/casesAdd', {
			title: '添加课程',
			category: _category
		})
	});
}

exports.update = function (req, res) {
	var _cases = req.params;
    Category.find({original:2}).sort({Sort: 1}).exec(function (err, _category) {
		Cases.findOne({
			"_id": _cases.id
		}, function (err, _cases) {
            var subStr=new RegExp('/attachment/')
            _cases.dataLink = _cases.dataLink.replace(subStr,'')
			res.render('admin/casesUpdate', {
				title: '编辑课程',
				category: _category,
				casesImg: _cases.imgPath.split(","),
                 casesTag:_cases.tag.split(","),
				cases: _cases
			})
		});
	});
}

//案例提交与更新
exports.save = function (req, res) {
	var _casesC = req.body;
	var _cases = {
			title: _casesC.title,
			address: _casesC.address,
			remark: _casesC.remark,
			imgPath:_casesC.imgPath,
			isIndex:_casesC.isIndex,
			typeId: _casesC.typeId,
			appraisal:_casesC.appraisal,
			numberPeople:_casesC.numberPeople,
			tag:_casesC.tag,
			dataLink:_casesC.dataLink,
			price:_casesC.price,
			guide:_casesC.guide,
			intro:_casesC.intro
		}

	if (_casesC._id) {
		var id = _casesC._id;
		Cases.update({
			_id: id
		}, _cases, function (err, category) {
			res.redirect("/admin/casesList");
		});
	} else {
		Cases.create(_cases, function (err, category) {
			res.redirect("/admin/casesList");
		});
	}

}

//提交与更新
exports.delete = function (req, res) {
	var id = req.params.id;
	Cases.remove({
		_id: id
	}, function (err, cases) {
		res.redirect("/admin/casesList");
	})
}
